<?php

class My_GData_GeoCoder {
	
	private $url;		
	private $countryName;		
	private $countryCode;		
	
	public function __construct()
	{
		$config = Zend_Registry::get('configuration');
		$key = $config->google->key;
		$this->countryName = $config->country->name;
		$this->countryCode = $config->country->code;
		
		$this->url = "http://maps.google.com/maps/geo?output=json&sensor=true&key={$key}&gl={$this->countryCode}&q=";
	}
	
	public function search( $query )
	{
//		$query.= ", {$this->countryName}";
//		Zend_Debug::dump( $this->url . urlencode($query) );
//		exit;
		
		$result = json_decode(file_get_contents($this->url . urlencode($query)));
		
//		Zend_Debug::dump( $result );
		
		if ( $result->Status->code != 200 ){
			
			return array();
			
			throw new Zend_Exception("error 200");			
		}
		
		$results = array(); 
        $filter = new My_Filter_CityName();
		
		foreach ($result->Placemark as $placemark){
			
			// por el momento no nos interesa otro pais
			if ( $placemark->AddressDetails->Country->CountryNameCode != $this->countryCode ){
				continue;
			}
			
			$result = array(			
				'latitud' => $placemark->Point->coordinates[1],
				'longitud' => $placemark->Point->coordinates[0],
				'presicion' => $placemark->AddressDetails->Accuracy,
			    'fullName' => $placemark->address,
			);	
			
			$Country = $placemark->AddressDetails->Country;
			
			$this->_province( $Country, $result );
			
			if ( isset($Country->Locality)){
				
				$Locality = $Country->Locality;
				
//				$this->_address( $Locality, $result );
				$this->_street( $Locality, $result );
				$this->_city( $Locality, $result );
				$this->_district( $Locality, $result );
			}
			
			elseif ( isset($Country->AdministrativeArea)){
				
				
				if ( isset($Country->AdministrativeArea->Locality) ) {
					$Locality = $Country->AdministrativeArea->Locality;					
				} else {
					$Locality = $Country->AdministrativeArea->SubAdministrativeArea->Locality;
				}
				
//				Zend_Debug::dump( $Locality );
//				$this->_address( $Locality, $result );
				$this->_street( $Locality, $result );
				$this->_city( $Locality, $result );
				$this->_district( $Locality, $result );
				
			}
			else { 
				continue; 
			}
			
			$this->_number( $placemark, $result );
			
	        $result['ciudad'] = $filter->filter( $result['ciudad'] );
			
	        $this->_check( $result );
	        
			$results[] = $result;			
			
		}
		
//		Zend_Debug::dump( $results );
//		exit;
		
		return $results;
	}
	
	
	protected function _district( $Locality, &$result )
	{
		if ( isset($Locality->DependentLocality->DependentLocalityName)){
			$result['barrio'] =  $Locality->DependentLocality->DependentLocalityName;
		} else {
			$result['barrio'] = null;
		}
	}
	
	protected function _city( $Locality, &$result )
	{
		if ( isset($Locality->LocalityName)){
			$result['ciudad'] =  $Locality->LocalityName;
		} else {
			$result['ciudad'] = null;
		}
	}
	
	protected function _street( $Locality, &$result )
	{
		if ( isset($Locality->DependentLocality->Thoroughfare->ThoroughfareName)){
			
			$ThoroughfareName = $Locality->DependentLocality->Thoroughfare->ThoroughfareName;
			
		} elseif (isset($Locality->Thoroughfare->ThoroughfareName)) {
			
			$ThoroughfareName = $Locality->Thoroughfare->ThoroughfareName;
			
		} else {
		    
		    $this->_log( "Undefined ThoroughfareName in " );
			return;
		}
		
		$result['calle'] = $ThoroughfareName;
	}
	
    protected function _number( $Placemark, &$result )
	{
	    $street = $result['calle'];
	    
	    $address = current(explode(',', $Placemark->address));
	    
		if( strstr($address, $street)){
		    $address = str_replace( $street, null, $address);
		}
		
		$result['numero'] = trim($address);
		
	}
	
//    protected function _address( $Locality, &$result )
//	{
//		if ( isset($Locality->DependentLocality->Thoroughfare->ThoroughfareName)){
//			
//			$ThoroughfareName = $Locality->DependentLocality->Thoroughfare->ThoroughfareName;
//			
//		} elseif (isset($Locality->Thoroughfare->ThoroughfareName)) {
//			
//			$ThoroughfareName = $Locality->Thoroughfare->ThoroughfareName;
//			
//		} else {
//			$logger = new My_Controller_Action_Helper_Log;
//			$logger->error( "Undefined ThoroughfareName in " . __FILE__ );
//			return;
//		}
//		
//		$data = str_replace(",","", $ThoroughfareName);	
//		$data = explode(" ", $ThoroughfareName);			
//		$result['numero'] = array_pop($data);
//		$result['calle'] = implode(" ", $data);
//	}
	
	protected function _province( $Country, &$result )
	{
		if ( isset($Country->AdministrativeArea->AdministrativeAreaName)){
			$result['provincia'] =  $Country->AdministrativeArea->AdministrativeAreaName;
		} else {
			$result['provincia'] = null;
		}
	}
	
    protected function _log( $msg )
    {
        $logger = new My_Controller_Action_Helper_Log;
		$logger->error( $msg . ' ' . __FILE__);
    
    }
    
    protected function _check( $result )
    {
        if ( 
                strlen( $result['calle']) < 4 ||
                !is_numeric( $result['numero']) ||
                strlen( $result['ciudad']) < 4 )
        {
            $this->_log( "Address error:" . Zend_Debug::dump($result, null, false) );
        }
        
    }
}


/*
VICENTE LOPEZ
http://maps.google.com/maps/geo?output=json&sensor=true&key=&q=maipu+500%2C+vicente+lopez%2C+Argentina

{
  "name": "maipu 500, vicente lopez, Argentina",
  "Status": {
    "code": 200,
    "request": "geocode"
  },
  "Placemark": [ {
    "id": "p1",
    "address": "Av Maipú 500, Vicente López, Buenos Aires, Argentina",
    "AddressDetails": {
   "Accuracy" : 8,
   "Country" : {
      "AdministrativeArea" : {
         "AdministrativeAreaName" : "Buenos Aires",
         "SubAdministrativeArea" : {
            "Locality" : {
               "LocalityName" : "Vicente López",
               "Thoroughfare" : {
                  "ThoroughfareName" : "Av Maipú 500"
               }
            },
            "SubAdministrativeAreaName" : "Vicente López"
         }
      },
      "CountryName" : "Argentina",
      "CountryNameCode" : "AR"
   }
},
    "ExtendedData": {
      "LatLonBox": {
        "north": -34.5322899,
        "south": -34.5349879,
        "east": -58.4771233,
        "west": -58.4798212
      }
    },
    "Point": {
      "coordinates": [ -58.4784828, -34.5336424, 0 ]
    }
  } ]
}

CAPITAL FEDERAL

http://maps.google.com/maps/geo?output=json&sensor=true&key=&q=Bouchard+500%2C+buenos+aires%2C+Argentina

{
  "name": "Bouchard 500, buenos aires, Argentina",
  "Status": {
    "code": 200,
    "request": "geocode"
  },
  "Placemark": [ {
    "id": "p1",
    "address": "Bouchard 500, Ciudad Autónoma de Buenos Aires, Capital Federal, Argentina",
    "AddressDetails": {
   "Accuracy" : 8,
   "Country" : {
      "CountryName" : "Argentina",
      "CountryNameCode" : "AR",
      "Locality" : {
         "DependentLocality" : {
            "DependentLocalityName" : "San Nicolás",
            "Thoroughfare" : {
               "ThoroughfareName" : "Bouchard 500"
            }
         },
         "LocalityName" : "Ciudad Autónoma de Buenos Aires"
      }
   }
},
    "ExtendedData": {
      "LatLonBox": {
        "north": -34.6004692,
        "south": -34.6031671,
        "east": -58.3678114,
        "west": -58.3705093
      }
    },
    "Point": {
      "coordinates": [ -58.3691697, -34.6018188, 0 ]
    }
  } ]
}


MAR DEL PLATA
http://maps.google.com/maps/geo?output=json&sensor=true&key=&q=cabildo+500%2C+mar+del+plata%2C+Argentina

{
  "name": "cabildo 500, mar del plata, Argentina",
  "Status": {
    "code": 200,
    "request": "geocode"
  },
  "Placemark": [ {
    "id": "p1",
    "address": "Mar del Plata, Buenos Aires, Argentina",
    "AddressDetails": {
   "Accuracy" : 4,
   "Country" : {
      "AdministrativeArea" : {
         "AdministrativeAreaName" : "Buenos Aires",
         "SubAdministrativeArea" : {
            "Locality" : {
               "LocalityName" : "Mar del Plata"
            },
            "SubAdministrativeAreaName" : "General Pueyrredón"
         }
      },
      "CountryName" : "Argentina",
      "CountryNameCode" : "AR"
   }
},
    "ExtendedData": {
      "LatLonBox": {
        "north": -37.9710628,
        "south": -37.9886529,
        "east": -57.5737868,
        "west": -57.6058016
      }
    },
    "Point": {
      "coordinates": [ -57.5897942, -37.9798584, 0 ]
    }
  } ]
}

*/




